package com.ukee.birthday.modules.controller;

import com.ukee.birthday.common.utils.R;
import com.ukee.birthday.modules.service.UploadExcelService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.ukee.birthday.config.WebConfig.FILEPATH;

/**
 * 上传文件
 */
@Slf4j
@RestController
@RequestMapping("common/file")
public class FileController extends AbstractController{

    @Resource
    private UploadExcelService uploadExcelService;

    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile[] files) throws IOException {
        if (files.length < 1) {
            return R.error("文件不能为空");
        }
        List<String> fileNameList = new ArrayList<>();
        for (MultipartFile file : files){
//            String[] ss = file.getOriginalFilename().split("\\.");
//            System.out.println("ss=============="+ss.toString());

            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID()+suffixName;
            File dest = new File(FILEPATH+fileName);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdir();
            }
            file.transferTo(dest.getAbsoluteFile());
            fileNameList.add(fileName);
        }
        return R.ok(200,fileNameList);
    }
    @ApiOperation(value = "导入Excel", notes = "导入Excel， file：文件")
    @RequestMapping("/uploadExcel")
//    public R uploadExcel(@RequestParam("file") MultipartFile[] files) throws IOException {
    public R uploadExcel(@RequestParam("file") MultipartFile[] files) throws IOException {
        System.out.println(files);
        if (files.length < 1) {
            return R.error("文件不能为空");
        }

        String msg = uploadExcelService.importProfession(files[0],7);
        if (!msg.equals("ok")) {
            return R.error(msg);
        }

        return R.ok(200,"");
    }
}
